<?php 

class Model{
	public $error;
	public $table;
	public $opt=array(
		'filed'=>'*',
		'where'=>'',
		'group'=>'',
		'having'=>'',
		'order'=>'',
		'limit'=>''
		);
	public function __construct($table=null)
	{
		if($table)$this->table =$table;/////////
		
		if(!@mysql_connect(C('DB_HOST'),C('DB_USER'),C('DB_PASSWORD'))){
			die('数据库链接失败');
		};
		mysql_query('set names '.C('DB_CHARSET'));


		if(!@mysql_select_db(C('DB_NAME'))){
			die('数据库连接失败');
		};
	}


	public function filed($arg)
	{
		$this->opt['filed']=$arg;
		return $this;//返回对象$this->db再次连接
	}
	public function where($arg)
	{
		$this->opt['where']=" where ".$arg;
		return $this;//返回对象$this->db再次连接
	}
	public function group($arg)
	{
		$this->opt['group']=" group by ".$arg;
		return $this;//返回对象$this->db再次连接
	}
	public function having($arg)
	{
		$this->opt['having']=" having ".$arg;
		return $this;//返回对象$this->db再次连接
	}
	public function order($arg)
	{
		$this->opt['order']=" order by ".$arg;
		return $this;//返回对象$this->db再次连接
	}
	public function limit($arg)
	{
		$this->opt['limit']=" limit ".$arg;
		return $this;//返回对象$this->db再次连接
	}

	//查找一条语句
	public function find()
	{
		$data=$this->select();
		return $data?current($data):$data;//////////
	}

	//查询
	public function select()
	{
		$sql="select {$this->opt['filed']} from ".$this->table.$this->opt['where'].$this->opt['group'].$this->opt['having'].
			$this->opt['order'].$this->opt['limit'];
			return $this->query($sql);
	}
	
	// 删除
	public function delete()
	{
		//必须有条件
		if (empty($this->opt['where'])) return false;
		$sql="delete from ".$this->table.$this->opt['where'];
		return $this->exe($sql);
	}

	//增
	public function insert($data)
	{	
		$sql="insert into ".$this->table;
		$filed=array_keys($data);//一维数组
		$value=array_values($data);/////////
		foreach ($value as $key => $v) {
			$value[$key]=addslashes($v);//输入的内容进行转义，防止'',""导致的报错
		}
		$sql.="(".implode(',', $filed).") values('".implode("','",$value)."')";//implode将一维数组转化为字符串通过','
		return $this->exe($sql);
	}

	//更新班级
	public function update($data)
	{
		// 必须有条件
		if (empty($this->opt['where']))return false;
		$sql="update ".$this->table." set ";
		foreach ($data as $key => $value) {
			$sql.=$key."='".$value."',";
		}
		$sql=substr($sql, 0,-1).$this->opt['where'];
		return $this->exe($sql);
	}

	//查询结果集的查询
	public function query($sql)
	{
		if (!$result=mysql_query($sql)) {
			die(mysql_error());
		}
		$data=array();
		while ($rows=mysql_fetch_assoc($result)) {
			$data[]=$rows;
		}
		return $data;
	}
	//没结果集的查询
	public function exe($sql)
	{
		if (mysql_query($sql)) {
			$insertid=mysql_insert_id();
			return $insertid?$insertid:true;///////
		}else{
			die(mysql_error());
		}
	}
	//获取受影响条数
	public function getAffectedRow(){
		return mysql_affected_rows();
	}

}

 ?>